const express = require('express');
const multer = require('multer');
const path = require('path');
const fs = require('fs').promises;
const { format } = require('date-fns');
const sanitize = require('sanitize-filename');
const iconv = require('iconv-lite'); // 用于处理不同编码

const app = express();

// 关键：在路由前添加中间件，强制设置编码
// app.use((req, res, next) => {
//   // 强制设置请求编码为UTF-8
//   req.setEncoding('utf8');
  
//   // 记录原始请求头（用于调试）
//   console.log('[请求头]', req.headers);
  
//   next();
// });



const PORT = 3000;
const UPLOAD_DIR = path.join(__dirname, 'uploads');
const FILES_DIR = path.join(__dirname,'files');
// const FILES_DIR ='C:\\Users\\lijinbei\\Desktop\\files';
const DEST_DIR = path.join(__dirname, 'dest');

const SYNC_DIR = path.join(__dirname,'now.json');

// 确保目录存在
async function ensureDirExists(dir) {
  try {
    await fs.mkdir(dir, { recursive: true });
  } catch (err) {
    console.error(`创建目录 ${dir} 失败:`, err);
  }
}

// 初始化
Promise.all([
  ensureDirExists(UPLOAD_DIR),
  ensureDirExists(FILES_DIR),
  ensureDirExists(DEST_DIR)
]).then(() => {
  console.log('目录初始化完成');
});

// 上传用户集
const userSet = new Map();

// 获取当前日期并格式化为文件夹名
const getCurrentDateFolder = () => {
  return format(new Date(), 'yyyy-MM-dd-HH-mm-ss');
};

// 创建按日期命名的文件夹
const createDateFolder = (namePrefix) => {
  const folderName = `${UPLOAD_DIR}/${namePrefix}-${getCurrentDateFolder()}`;
  return folderName;
};

// 配置 multer 存储引擎
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    const textInput = req.body.textInput;
    
    if(!userSet.has(textInput)){
      const folder = createDateFolder(textInput);
      userSet.set(textInput, folder);
      fs.mkdir(folder, { recursive: true }).catch(err => {
        console.error('创建上传目录失败:', err);
      });
    }
    cb(null, userSet.get(textInput));
  },
  filename: (req, file, cb) => {
    try {

      // 关键修复：将ISO-8859-1编码的文件名转回UTF-8
      // 1. 将乱码字符串转换为二进制数据
      const isoBuffer = Buffer.from(file.originalname, 'binary');
      
      // 2. 将二进制数据按UTF-8解码
      const utf8Filename = iconv.decode(isoBuffer, 'utf8');
      
      // console.log('[UTF-8解码后]', utf8Filename);

        // 先解码文件名
        // const decodedFilename = decodeURIComponent(file.originalname);
        // // 再进行安全处理
        // console.log("原file.originalname：",file.originalname);
        // console.log("解码file.originalname：",decodedFilename);
        const safeFilename = sanitize(utf8Filename, {
            replacement: '_',
            keepUnicode: true
        });
        // console.log("修改后file.originalname：",safeFilename);
        cb(null, safeFilename);
    } catch (error) {
        console.error('文件名处理错误:', error);
        // 处理错误情况，使用默认文件名
        cb(error, file.originalname);
    }
  }
});

const upload = multer({ storage });

// 处理文件上传的路由
app.post('/api/upload', upload.array('files'), async (req, res) => {
  try {
    if (!req.files || req.files.length === 0) {
      return res.status(400).json({ error: '未选择文件' });
    }
    
    // const fileNames = req.files.map(file => Buffer.from(file.filename, 'utf8').toString('latin1'));
    const fileNames = req.files.map(file => file.filename);
    // console.log(fileNames);
    const textInput = req.body.textInput;
    
    // 复制到目标目录
    const src = userSet.get(textInput);
    const srcSplit = src.split('/');
    // console.log(srcSplit);
    const destFolder = `${DEST_DIR}/${srcSplit[srcSplit.length-1]}`;
    
    await fs.mkdir(destFolder, { recursive: true });
    
    // 复制文件
    for (const file of req.files) {
      const srcPath = path.join(src, file.filename);
      const destPath = path.join(destFolder, file.filename);
      await fs.copyFile(srcPath, destPath);
    }
    
    // 复制完成后删除临时文件夹
    await fs.rm(src, { recursive: true, force: true });
    userSet.delete(textInput);
    
    res.status(200).json({ message: '文件上传成功', fileNames });
  } catch (error) {
    console.error('文件上传出错:', error);
    res.status(500).json({ error: '文件上传失败' });
  }
});

// 下载API
app.get('/api/download', async (req, res) => {
  const encodedPath = req.query.path;
  console.log(encodedPath);
  if (!encodedPath) {
    return res.status(400).json({ error: '缺少文件路径' });
  }
  
  try {
    const decodedPath = decodeURIComponent(encodedPath);
    // const safePath = path.normalize(path.join(FILES_DIR, decodedPath));
    const safePath = path.normalize(decodedPath);
    
    if (!safePath.startsWith(FILES_DIR)) {
      console.log('访问拒接');
      return res.status(403).json({ error: '访问被拒绝' });
    }
    
    const stats = await fs.stat(safePath);
    
    if (stats.isDirectory()) {
      return res.status(400).json({ error: '无法下载目录' });
    }
    
    // console.log('wuhu');

    res.download(safePath, (err) => {
      if (err) {
        console.error('下载错误:', err);
        res.status(500).json({ error: '下载失败' });
      }
    });
    // console.log('wuhu');
  } catch (err) {
    console.error('下载错误:', err);
    res.status(500).json({ error: '下载失败' });
  }
});

// 搜索API - 
// 1. 读取now.json 
// 2. 递归搜索 x 小时内创建的文件夹
// 3. 返回所有文件
app.get('/api/search', async (req, res) => {
  const query = req.query.query || 'abcd';
  // console.log(query);
  try {
    const fileTreeForNow = await fs.readFile(SYNC_DIR, {
      encoding: "utf8",
      flag: "r",
    });

    const obj = JSON.parse(fileTreeForNow);
    
    const childs = obj.children;

    // const timeLimit = Date.now() - 8000 * 288000;

    const results = searchFilesWithQuery(childs, query/*, timeLimit*/);
    res.json({ query, results });
  } catch (err) {
    console.error('搜索错误:', err);
    res.status(500).json({ error: '搜索失败' });
  }
});

function searchFilesWithQuery(childs, query) {
  const results = [];
  const queryCon = String(query).toLowerCase();
  // console.log(queryCon);
  for (const element of childs) {
    // if (element.mtime < timeLimit) {
    //   // console.log('here')
    //   continue;
    // }
    if (element.name.toLowerCase().includes(queryCon)) {
      // console.log("Enter");
      if (element.type === "directory") {
        const children = getAllFiles(element.children); // 递归获取子目录内容
        results.push({
          name: element.name,
          type: element.type,
          path: element.path,
          children,
        });
      } else {
      results.push({
        name: element.name,
        type: element.type,
        path: element.path,
        children: [],
      });
    }
    }
  }
  return results;
}

function getAllFiles(childs) {
  const temp = [];
  for (const element of childs) {
    if (element.type === "directory") {
      const children = getAllFiles(element.children); // 递归获取子目录内容
      temp.push({
        name: element.name,
        type: element.type,
        path: element.path,
        children,
      });
    } else {
      temp.push({
        name: element.name,
        type: element.type,
        path: element.path,
        children: [],
      });
    }
  }
  return temp;
}

// 静态文件服务
app.use(express.static(path.join(__dirname, 'public')));

// 路由 - 文件浏览器主页
app.get('/browser', (req, res) => {
  res.sendFile(path.join(__dirname, 'public', 'browser.html'));
});

// 路由 - 文件上传主页
app.get('/upload', (req, res) => {
  res.sendFile(path.join(__dirname, 'public', 'upload.html'));
});

// 根路径重定向到上传页面
app.get('/', (req, res) => {
  res.redirect('/upload');
});

// 启动服务器
app.listen(PORT, () => {
  console.log(`服务器运行在 http://localhost:${PORT}`);
  console.log(`上传目录: ${UPLOAD_DIR}`);
  console.log(`文件目录: ${FILES_DIR}`);
  console.log(`目标目录: ${DEST_DIR}`);
});    
